import axios from 'axios'
import event from './event'

const request = axios.create({ baseURL: process.config.baseURL })

// request拦截器
request.interceptors.request.use(config => {
  if (process.config.cookie) {
    config.headers['Cookie'] = process.config.cookie // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  if (process.config.csrftoken) {
    if (!config.params) {
      config.params = {}
    }
    config.params.csrftoken = process.config.csrftoken
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})
// respone拦截器
request.interceptors.response.use(
  response => {
    if (response.headers['set-cookie']) {
      process.config.cookie = response.headers['set-cookie'].map(it => {
        return it.split(';')[0]
      }).join(';')
    }
    if (/(login.jsp)/.test(response.request.path)) {
      event.emit('logout')
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error)// for debug
    return Promise.reject(error)
  }
)

export default request
